package com.study.other3;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class CountNumber {
    public static void main(String[] args) throws Exception {
        ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(3);
        LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>();

        Runnable runnable1 = () -> {
            int a = ((int) (Math.random() * 11));
            try {
                queue.put(a);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "生产消息");
        };

        Runnable runnable2 = () -> {
            int a = ((int) (Math.random() * 11));
            try {
                queue.put(a);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "生产消息");
        };
        scheduledThreadPoolExecutor.scheduleAtFixedRate(runnable1, 0L, 500L, TimeUnit.MILLISECONDS);
        scheduledThreadPoolExecutor.scheduleAtFixedRate(runnable2, 0L, 500L, TimeUnit.MILLISECONDS);

        Map<Integer, Integer> map = new HashMap<>();
        Runnable runnable3 = () -> {
            Integer take = null;
            try {
                take = queue.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (Objects.isNull(map.get(take))) {
                map.put(take, 1);
            } else {
                map.put(take, map.get(take) + 1);
            }
        };
        scheduledThreadPoolExecutor.scheduleAtFixedRate(runnable3, 0L, 0L, TimeUnit.MILLISECONDS);
        System.out.println(map.toString());
    }
}
